﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NK.Mvc3.Business;
using NK.Mvc3.Lib;
using NK.Mvc3.Models;
using NK.Mvc3.DBL;
using NK.Mvc3.ViewModels;

namespace NK.Mvc3.Controllers
{ 
    public class StoreOutputController : Controller
    {
        private StoreContext db = new StoreContext();

        public ViewResult Import()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Import(StoreOutput storeOutput)
        {
            var listDetails = new List<StoreOutputDetail>();
            foreach (string item in Request.Files)
            {
                var file = Request.Files[item];
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
                    file.SaveAs(path);

                    //ProductMasterImportVM model = new ProductMasterImportVM();
                    //model.FileName = fileName;
                    ProcessExcelData(path, storeOutput);

                    //ViewBag.FileName = fileName;
                    //model.IsSuccess = true;

                    break;
                }
            }

            //return View(storeOutput);
            //return ImportConfirm(storeOutput);
            return RedirectToAction("ImportConfirm", new { id=storeOutput.ID });
        }

        private void ProcessExcelData(string path, StoreOutput storeOutput)
        {
            //db.StoreOutputs.Add(storeOutput);
            storeOutput.StoreOutputDetails = new Collection<StoreOutputDetail>();

            Microsoft.Office.Interop.Excel.Application xlApp;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            Microsoft.Office.Interop.Excel.Range range;

            //File excelFile = file.

            xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Q_Rep1120.rpt");
            //(Excel.Worksheet) xlWorkBook.Worksheets.get_Item("PO-GRN D1");

            range = xlWorkSheet.UsedRange;
            int toLine = 40;
            int fromLine = 17;
            for (int rCnt = fromLine; rCnt <= toLine; rCnt++)
            {
                var storeOutputDetail = new StoreOutputDetail();
                var barcode = (string)(range.Cells[rCnt, 3] as Microsoft.Office.Interop.Excel.Range).Value2;
                storeOutputDetail.ProductInfo = db.ProductInfos.Where(p => p.BarCode == barcode).SingleOrDefault();
                
                if (storeOutputDetail.ProductInfo == null)
                {
                    throw new Exception("Cannot find productinfo with barcode:" + barcode);
                }
                storeOutputDetail.ProductInfoID = storeOutputDetail.ProductInfo.ID;
                storeOutputDetail.Quantity = int.Parse((range.Cells[rCnt, 7] as Microsoft.Office.Interop.Excel.Range).Value2);
                storeOutputDetail.CostOutput = double.Parse((range.Cells[rCnt, 8] as Microsoft.Office.Interop.Excel.Range).Value2);
                storeOutputDetail.TotalCost = double.Parse((range.Cells[rCnt, 9] as Microsoft.Office.Interop.Excel.Range).Value2);
                storeOutput.StoreOutputDetails.Add(storeOutputDetail);
            }
            
            var storeIO = new StoreIO(db);
            storeIO.AddStoreOutput(storeOutput);
            storeIO.Save();
            //db.StoreOutputs.Add(storeOutput);
            //db.SaveChanges();

            xlWorkBook.Close(false, null, null);
            //xlWorkBook.Close();
            xlApp.Quit();

            FileUtility.ReleaseObject(xlWorkSheet);
            FileUtility.ReleaseObject(xlWorkBook);
            FileUtility.ReleaseObject(xlApp);

        }

        public ActionResult ImportConfirm( int id)
        {
            var obj = db.StoreOutputs.Include(s => s.StoreOutputDetails).Where(s => s.ID == id).SingleOrDefault();

            return View(obj);
        }

        [HttpPost]
        public ActionResult ImportConfirm(StoreOutput storeOutput, string Remove, string Confirm)
        {
            if (!string.IsNullOrEmpty(Remove) && string.IsNullOrEmpty(Confirm))
            {
                //Remove storeoutput
                var storeOut = db.StoreOutputs.Find(storeOutput.ID);
                var storeIO=new StoreIO(db);
                storeIO.RemoveStoreOutput(storeOut);
                storeIO.Save();
                //db.StoreOutputs.Remove(storeOutput);
                //db.SaveChanges();
            }
            return RedirectToAction("Index");
        }


        //
        // GET: /StoreOutput/

        public ViewResult Index()
        {
            return View(db.StoreOutputs.ToList());
        }

        //
        // GET: /StoreOutput/Details/5

        public ViewResult Details(int id)
        {
            StoreOutput storeoutput = db.StoreOutputs.Find(id);
            return View(storeoutput);
        }

        //
        // GET: /StoreOutput/Create

        //public ActionResult Create()
        //{
        //    return View();
        //} 

        ////
        //// POST: /StoreOutput/Create

        //[HttpPost]
        //public ActionResult Create(StoreOutput storeoutput)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        db.StoreOutputs.Add(storeoutput);
        //        db.SaveChanges();
        //        return RedirectToAction("Index");  
        //    }

        //    return View(storeoutput);
        //}
        
        //
        // GET: /StoreOutput/Edit/5
 
        public ActionResult Edit(int id)
        {
            StoreOutput storeoutput = db.StoreOutputs.Find(id);
            return View(storeoutput);
        }

        //
        // POST: /StoreOutput/Edit/5

        [HttpPost]
        public ActionResult Edit(StoreOutput storeoutput)
        {
            if (ModelState.IsValid)
            {
                db.Entry(storeoutput).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(storeoutput);
        }

        //
        // GET: /StoreOutput/Delete/5
 
        public ActionResult Delete(int id)
        {
            StoreOutput storeoutput = db.StoreOutputs.Find(id);
            return View(storeoutput);
        }

        //
        // POST: /StoreOutput/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            StoreOutput storeoutput = db.StoreOutputs.Find(id);

            var storeIO = new StoreIO(db);
            storeIO.RemoveStoreOutput(storeoutput);
            storeIO.Save();

            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }


        
    }
}